Page({
  data: {
    isLoading: true,
    errorMsg: '',
    taskList: [],
    selectedTask: {},
    selectedPatrol: {},
    selectedPoint: {},
    mapLongitude: 116.407526,
    mapLatitude: 39.90403,
    currentLocation: null,
    signedCount: 0,
    lastSignTime: '',
    lastSignArea: '',
    showSignModal: false
  },

  onLoad() {
    this.fetchTaskList();
    this.getCurrentLocation();
  },

  // 获取任务列表
  fetchTaskList() {
    this.setData({ isLoading: true });
    wx.request({
      url: 'http://localhost:8080/api/wechat/with-collections',
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      success: (res) => {
        if (res.data.code === 200 && res.data.data) {
          const processedTasks = this.processTaskData(res.data.data);
          this.setData({
            taskList: processedTasks,
            errorMsg: ''
          });
          
          if (processedTasks.length > 0) {
            this.setData({ selectedTask: processedTasks[0] }, () => {
              this.initPatrolAndPoint();
            });
          }
        } else {
          this.setData({
            errorMsg: res.data.message || `请求失败: ${res.statusCode}`
          });
        }
      },
      fail: (err) => {
        this.setData({
          errorMsg: err.errMsg || '网络请求失败'
        });
      },
      complete: () => {
        this.setData({ isLoading: false });
      }
    });
  },

  // 处理任务数据
  processTaskData(tasks) {
    return tasks.map(task => ({
      ...task,
      officerNames: task.officers.flat().map(o => o.officerName).join('、'),
      patrolPointCollections: (task.patrolPointCollections || []).map(p => ({
        ...p,
        isExpanded: false
      }))
    }));
  },

  // 初始化巡逻区域和签到点
  initPatrolAndPoint() {
    const { selectedTask } = this.data;
    if (selectedTask.patrolPointCollections?.length > 0) {
      const [firstPatrol] = selectedTask.patrolPointCollections;
      const [firstPoint] = firstPatrol.patrolPoints || [];
      this.setData({
        selectedPatrol: firstPatrol,
        selectedPoint: firstPoint
      });
    }
  },

  // 获取当前位置
  getCurrentLocation() {
    wx.getLocation({
      type: 'wgs84',
      success: (res) => {
        this.setData({
          mapLongitude: res.longitude,
          mapLatitude: res.latitude,
          currentLocation: `${res.longitude.toFixed(6)},${res.latitude.toFixed(6)}`
        });
      },
      fail: (err) => {
        wx.showToast({ title: '获取位置失败', icon: 'none' });
        console.error('位置获取失败:', err);
      }
    });
  },

  // 打开模态框（增加数据验证）
  openSignModal() {
    const { taskList } = this.data;
    if (!taskList || !taskList.length) {
      return wx.showToast({ title: '暂无可用任务', icon: 'none' });
    }
    
    if (!this.validateModalData()) {
      return wx.showToast({ title: '数据加载中，请稍后', icon: 'none' });
    }
    
    this.getCurrentLocation();
    this.setData({ showSignModal: true });
  },

  // 关闭模态框
  closeSignModal() {
    this.setData({ showSignModal: false });
  },

  // 蒙层点击事件（防止误触）
  onMaskTap(e) {
    // 确保只有点击蒙层本身时才关闭
    if (e.target.dataset.type === 'mask') {
      this.closeSignModal();
    }
  },

  // 数据验证
  validateModalData() {
    const { selectedTask, selectedPatrol, selectedPoint } = this.data;
    return (
      selectedTask.shiftId &&
      selectedPatrol.patrolPointCollectionId &&
      selectedPoint.pointId
    );
  },

  // 选择任务
  onTaskChange(e) {
    const { taskList } = this.data;
    const selectedTask = taskList[e.detail.value];
    this.setData({ selectedTask }, () => {
      this.initPatrolAndPoint();
    });
  },

  // 选择巡逻区域
  onPatrolChange(e) {
    const { selectedTask } = this.data;
    const selectedPatrol = selectedTask.patrolPointCollections[e.detail.value];
    this.setData({
      selectedPatrol,
      selectedPoint: selectedPatrol.patrolPoints?.[0] || {}
    });
  },

  // 选择签到点
  onPointChange(e) {
    const { selectedPatrol } = this.data;
    this.setData({
      selectedPoint: selectedPatrol.patrolPoints[e.detail.value]
    });
  },

  // 提交签到（增加数据验证）
  submitSign() {
    if (!this.validateModalData()) {
      return wx.showToast({ title: '请完善签到信息', icon: 'none' });
    }
    
    const { selectedTask, selectedPatrol, selectedPoint, mapLongitude, mapLatitude } = this.data;
    if (!mapLongitude || !mapLatitude) {
      return wx.showToast({ title: '位置信息缺失', icon: 'none' });
    }
    const requestData ={
      officerId: wx.getStorageSync('currentOfficer').officerId,
      shiftId: selectedTask.shiftId,
      patrolCollectionId: selectedPatrol.patrolPointCollectionId,
      pointId: selectedPoint.pointId,
      longitude: mapLongitude,
      latitude: mapLatitude
    };
    console.log('提交签到请求数据:', requestData);
    wx.showLoading({ title: '提交中...', mask: true });
    wx.request({
      url: 'http://localhost:8080/api/patrol/check-in',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${wx.getStorageSync('token')}`
      },
      data: requestData,
      success: (res) => {
        console.log(res);
        console.log(res.data.data);
        if (res.data.data) {
          wx.showToast({ title: '签到成功', icon: 'success' });
          this.setData({
            signedCount: (this.data.signedCount || 0) + 1,
            lastSignTime: new Date().toLocaleTimeString(),
            lastSignArea: selectedPoint.pointName
          });
          this.closeSignModal();
          this.fetchTaskList();
        } else {
          wx.showToast({ title: '签到失败', icon: 'none' });
        }
      },
      fail: (err) => {
        wx.showToast({ title: '网络错误', icon: 'none' });
        console.error('签到失败:', err);
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  }
});